<template>
  <div flex-1 flex overflow-hidden>
    <div w-180px h-full bg="#001529" overflow-y-auto overflow-x-hidden>
      <div flex-center w-full h-full v-if="loadingSite">
        <a-spin :spinning="loadingSite"> </a-spin>
      </div>
      <a-menu theme="dark" w-full v-model:selected-keys="current" v-else>
        <a-menu-item v-for="item in siteList" :key="item.websiteCode">
          {{ item.websiteName }}
        </a-menu-item>
      </a-menu>
    </div>
    <div flex-1 p-4 overflow-y-auto>
      <a-button mb-4 type="primary" @click="() => showAdd()">新建</a-button>
      <a-table
        :columns="columns"
        :data-source="data.dataSource"
        :bordered="true"
        :pagination="false"
        :loading="loadingTable"
        size="small"
      >
        <template #bodyCell="{ record, column, value }">
          <div flex flex-wrap gap-y-2 v-if="column.dataIndex == 'option'">
            <a-tag
              v-for="item in (record as CategorySplit).split.splitConditionOptions"
              :key="item.option_name"
            >
              {{ item.option_name }}
            </a-tag>
          </div>
          <span v-if="column.dataIndex == 'status'">
            {{ value == 0 ? '未发布' : '已发布' }}
          </span>
          <span v-if="column.dataIndex == 'split'">
            {{ value.categoryName }}
          </span>
          <template v-if="column.dataIndex == 'action'">
            <a-popconfirm @confirm="confirmPublish(record)" title="提示">
              <template #description>
                <p>发布后，再次编辑可能会导致拆分类目的合并工作需要重置</p>
                <p>确定要发布吗？</p>
              </template>
              <a-button type="link" :disabled="record.status != 0">
                发布
              </a-button>
            </a-popconfirm>
            <a-button type="link" @click="showEdit(record)"> 编辑 </a-button>
            <a-popconfirm
              title="提示"
              :description="`是否删除${record.originCategoryName}?`"
              @confirm="confirmRemove(record)"
            >
              <a-button type="link"> 删除 </a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </div>
    <split-modal ref="splitRef" @ok="handleOk"></split-modal>
  </div>
</template>

<script lang="ts" setup>
import { fetchWebsiteList } from '@/api/website';
import { SiteConfig } from '@/store/config';
import splitModal from './splitModal.vue';
import {
  CategroySplitItem,
  getCategorySplits,
  publishSplits,
  removeCategorySplits,
} from '@/api/split';
import { CategorySplit, SplitItemOption } from './type';

const splitRef = ref<InstanceType<typeof splitModal>>();

const route = useRoute();
const init = ref(false);
const current = ref<string[]>([]);
const siteList = ref<SiteConfig[]>([]);
const loadingSite = ref(false);
const loadingTable = ref(false);
const getWebsites = async () => {
  loadingSite.value = true;
  const res = await fetchWebsiteList();
  loadingSite.value = false;
  useRes(res, () => {
    siteList.value = res.data;
    const websiteCode = route.query.websiteCode as string;
    if (!init.value && websiteCode) {
      current.value = [websiteCode];
      return;
    }
    if (res.data.length) {
      current.value = [res.data[0].websiteCode];
    }
  });
};

const websiteCode = computed(() => {
  const [code] = current.value;
  return code || '';
});

getWebsites();
const showAdd = (categoryCode?: string) => {
  websiteCode.value && splitRef.value?.add(websiteCode.value, categoryCode);
};
const showEdit = record => {
  splitRef.value?.edit(
    websiteCode.value,
    cloneDeep(data.value.dataMap.get(record.originCategoryCode))
  );
};

const columns = ref([
  {
    title: '源类目',
    dataIndex: 'originCategoryName',
    width: 150,
    customCell: data => {
      return {
        rowSpan: data.rowSpan,
      };
    },
  },
  {
    title: '对应条件',
    dataIndex: 'splitConditionName',
    width: 150,
    customCell: data => {
      return {
        rowSpan: data.rowSpan,
      };
    },
  },
  {
    title: '对应选项',
    dataIndex: 'option',
  },
  {
    title: '拆分类目',
    dataIndex: 'split',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 80,
    customCell: data => {
      return {
        rowSpan: data.rowSpan,
      };
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '220px',
    customCell: data => {
      return {
        rowSpan: data.rowSpan,
      };
    },
  },
]);

const categoryList = ref<CategroySplitItem[]>([]);
const router = useRouter();
const fetchCategoryList = async () => {
  const { websiteCode: _websiteCode, categoryId: _categoryId } = route.query;
  loadingTable.value = true;
  const res = await getCategorySplits({ websiteCode: websiteCode.value });
  useRes(res, () => {
    categoryList.value = res.data;
    if (!init.value && _websiteCode && _categoryId) {
      init.value = true;
      showAdd(_categoryId as string);
      router.replace({ query: {} });
    }
  });
  loadingTable.value = false;
};

const data = computed(() => {
  const dataMap = new Map();
  const dataSource = categoryList.value.reduce((arr, item) => {
    dataMap.set(item.originCategoryCode, item);
    const list: CategorySplit[] = item.splits.map((split, idx) => {
      return {
        rowSpan: idx == 0 ? item.splits.length : 0,
        split: {
          categoryName: split.categoryName,
          splitConditionOptions: parseJson<SplitItemOption[]>(
            split.splitConditionOptions,
            []
          ),
        },
        ...omit(item, 'splits'),
      };
    });
    return arr.concat(list);
  }, [] as CategorySplit[]);
  return {
    dataSource,
    dataMap,
  };
});
watchEffect(() => {
  if (websiteCode.value) {
    fetchCategoryList();
  }
});

const handleOk = () => {
  fetchCategoryList();
};

const confirmPublish = async record => {
  const { originCategoryCode } = record as CategorySplit;
  const res = await publishSplits(websiteCode.value, originCategoryCode);
  useRes(res, () => {
    message.success('发布成功');
    fetchCategoryList();
  });
};

const confirmRemove = async record => {
  const { originCategoryCode } = record as CategorySplit;
  const res = await removeCategorySplits(websiteCode.value, originCategoryCode);
  useRes(res, () => {
    message.success('删除成功');
    fetchCategoryList();
  });
};
</script>
